package com.example.administrator.base.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.administrator.base.baseActivity.BaseActivity;
import com.example.administrator.base.bean.OrderLisetBean;
import com.example.administrator.base.R;
import com.example.administrator.base.util.GsonTools;
import com.example.administrator.base.util.SharedPreferencesUtils;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OrderList extends BaseActivity {

    @InjectView(R.id.Toolbar)
    android.support.v7.widget.Toolbar Toolbar;
    @InjectView(R.id.list)
    ListView list;
    @InjectView(R.id.swip)
    TwinklingRefreshLayout swip;
    SimpleAdapter adapter;
    int page = 1;
    String totlePage;
    List<Map<String, Object>> datalist ;
    Map<String, Object> map ;
    List<OrderLisetBean.InfosBean> listbean;
    SweetAlertDialog sweetAlertDialog ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_list);
        ButterKnife.inject(this);
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setCanceledOnTouchOutside(false);
        sweetAlertDialog.setTitleText("加载中");
        datalist = new ArrayList<>();
        listbean=new ArrayList<>();
        Toolbar.setTitle("赳猎人");
        Toolbar.setSubtitle("我的工单");
        setSupportActionBar(Toolbar);
        Toolbar.setNavigationIcon(R.drawable.backbar);
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        sweetAlertDialog.show();
        getOrderList(page);
        adapter = new SimpleAdapter(this,datalist,R.layout.orderlistitem,
                new String[]{"name","number","img","time"},
                new int[]{R.id.tv_pointName,R.id.tv_number,R.id.im_stage,R.id.tv_timex});
        list.setAdapter(adapter);
        swip.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                listbean.clear();
                datalist.clear();
                page=1;
                getOrderList(page);


            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);


                if (page== Integer.parseInt(totlePage)){
                    swip.finishLoadmore();
                    Toast.makeText(OrderList.this,"别拉了，已经到底啦！",Toast.LENGTH_SHORT).show();
                }else {
                    page+=1;
                    getOrderList(page);
                }

            }
        });
    }

    @Override
    protected void onResponseSuccess(Response response, String action) {

    }

    @Override
    protected void onResponseFailure(Throwable e, String action) {

    }

    /*获取我的工单列表*/
    public void getOrderList(int number) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "QUERYMYACCEPTLIST")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(OrderList.this, "adminId", "")))
                .add("page", String.valueOf(number))
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/dispatcher?")
                .post(formBody)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response ;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("337101", ""+string);
                        final OrderLisetBean mse = GsonTools.changeGsonToBean(string, OrderLisetBean.class);
                        if (mse != null) {
                        if (mse.getCode() == 1) {
                            totlePage = mse.getAllMyListTotalPages();
                            listbean.addAll(mse.getInfos());
                            for (int i = 0; i < mse.getInfos().size(); i++) {
                                map = new HashMap<>();
                                map.put("time", mse.getInfos().get(i).getStartTime());
                                if (mse.getInfos().get(i).getListFlag() == 0) {
                                    map.put("name", "工单类型 ： 调度单");
                                    map.put("number", "需调度车辆：" + mse.getInfos().get(i).getBicycleNum());
                                } else {
                                    map.put("name", "工单类型 ： 维修单");
                                    map.put("number", "需维修车辆：" + mse.getInfos().get(i).getBicycleNum());
                                }
                                switch (mse.getInfos().get(i).getProcessFlag()) {
                                    case 0:
                                        map.put("img", R.drawable.order2);
                                        break;
                                    case 1:
                                        map.put("img", R.drawable.order4);
                                        break;
                                    case 2:
                                        map.put("img", R.drawable.order1);
                                        break;
                                    case 3:
                                        map.put("img", R.drawable.order3);
                                        break;
                                }
                                datalist.add(map);
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyDataSetChanged();
                                    swip.finishRefreshing();
                                    swip.finishLoadmore();
                                    sweetAlertDialog.dismiss();
                                }
                            });

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(OrderList.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                }
                            });
                        }
                    }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(OrderList.this, "数据异常请重试", Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                }
                            });
                        }
                    } else {
                        throw new Exception("Unexpected code " + response);
                    }
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(OrderList.this, "数据异常请重试", Toast.LENGTH_LONG).show();
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
